package com.dukk.gis.tools.extensions.shadow;

import com.dukk.gis.tools.BufferTool;
import org.locationtech.jts.geom.*;
import java.util.HashSet;
import java.util.Set;

/**
 *  虚拟link计算,link插点
 */
public class VirtualLine {


    GeometryFactory  geometryFactory = new GeometryFactory();

    private Geometry lineGeo;

    Set<Coordinate> linkCoordinateSet = new HashSet<>();

    private double bufferM = 0.5;

    public VirtualLine(Geometry lineGeo){
        this.lineGeo = lineGeo;

        Coordinate[] coordinates = this.lineGeo.getCoordinates();
        for(Coordinate coordinate : coordinates){
            this.linkCoordinateSet.add(coordinate);
        }

    }


    public void resetLinkGeo(Geometry linkPartGeo){

        if(null==linkPartGeo || linkPartGeo.isEmpty()){
            return;
        }

        Coordinate[] paCoordinates = linkPartGeo.getCoordinates();

        Coordinate[] linkCoordinates = this.lineGeo.getCoordinates();

        CoordinateList coordinatesLinkList = new CoordinateList();
        coordinatesLinkList.add(linkCoordinates, false);

        boolean isReset = false;
        for(Coordinate paCoordinate : paCoordinates){
            if(!this.linkCoordinateSet.contains(paCoordinate)){
                for(int i =0; i<coordinatesLinkList.size();i++){
                    int next = i+1;
                    if(next >= coordinatesLinkList.size()){
                        break;
                    }

                    Coordinate beforeC = coordinatesLinkList.getCoordinate(i);
                    Coordinate nextC = coordinatesLinkList.getCoordinate(next);

                    Coordinate[] coordinateLine = new Coordinate[2];
                    coordinateLine[0] = beforeC;
                    coordinateLine[1] = nextC;
                    LineString lineString = geometryFactory.createLineString(coordinateLine);

                    Point point = geometryFactory.createPoint(paCoordinate);

                    Geometry bufferCm = BufferTool.bufferCapFat(lineString, this.bufferM);


                    if(bufferCm.contains(point)){
                        coordinatesLinkList.add(next, paCoordinate);
                        this.linkCoordinateSet.add(paCoordinate);
                        isReset = true;
                        break;
                    }

                }
            }
        }

        if(isReset){
           this.lineGeo = geometryFactory.createLineString(coordinatesLinkList.toCoordinateArray());
        }

    }

    public Geometry getLineGeo() {
        return lineGeo;
    }

    public void setLineGeo(Geometry linkGeo) {
        this.lineGeo = linkGeo;
    }



}
